package com.ch.engine.utils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

/**
 * 复利计算器，用于计算本金按固定周期增长率增长后的总金额
 *
 * @author wangchunhui
 * @date 2025/8/27 9:49
 */
public class CompoundInterestUtil {

    private final static LocalDate START_DATE = LocalDate.of(2025, 8, 13);

    /**
     * 计算复利增长后的总金额
     *
     * @param principal 本金
     * @param rate      每期增长率（小数形式，如0.02表示2%）
     * @param periods   期数
     * @return 增长后的总金额
     */
    public static BigDecimal calculateCompoundInterest(BigDecimal principal, BigDecimal rate, int periods) {
        // 公式: 本金 * (1 + 增长率)^期数
        BigDecimal onePlusRate = BigDecimal.ONE.add(rate);
        BigDecimal power = onePlusRate.pow(periods);
        return principal.multiply(power).setScale(2, RoundingMode.HALF_UP);
    }

    public static void main(String[] args) {
        // 本金5万
        BigDecimal principal = new BigDecimal("50000");
        // 每7天涨2% => 每天涨率
        BigDecimal weeklyRate = new BigDecimal("0.02");
        BigDecimal dailyRate = weeklyRate.divide(new BigDecimal("7"), 10, RoundingMode.HALF_UP);
        // 天数（比如3年）
        int periods = 365 * 3;

        BigDecimal result = calculateCompoundInterest(principal, dailyRate, periods);
        BigDecimal dailyRateScale = dailyRate.multiply(new BigDecimal("100")).setScale(4, RoundingMode.HALF_UP);
        System.out.println("本金" + principal + "，每7天涨" + weeklyRate.multiply(new BigDecimal("100")) + "%，折合每天涨" + dailyRateScale + "%，" + periods / 365 + "年后的金额为: " + result + "元");

        System.out.println("==========================================");
        System.out.println("计算过程:");
        System.out.println("本金: " + principal + "元");
        System.out.println("每天增长率: " + dailyRateScale + "%");
        System.out.println("天数: " + periods + "天");
        System.out.println("公式: 本金 × (1 + 每日增长率)^天数");
        System.out.println("结果: " + principal + " × (1 + " + dailyRate + ")^" + periods + " = " + result + "元");
        System.out.println("==========================================");

        LocalDate endDate = LocalDate.of(2025, 9, 23);
        int days = (int) ChronoUnit.DAYS.between(START_DATE, endDate) + 1;
        BigDecimal currentAmount = calculateCompoundInterest(principal, dailyRate, days);
        System.out.println(endDate + "日总资金应该要达到：" + currentAmount + "元");
        System.out.println("==========================================");
    }
}
